package com.mumulx.check.web.config.rabbit;

import com.mumulx.check.redis.entity.CheckPartContants;
import com.mumulx.check.service.service.CheckpartSendLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class RabbitConfig {
    @Autowired
    CachingConnectionFactory cachingConnectionFactory;
    //@Autowired
    @Resource
    CheckpartSendLogService checkpartSendLogService;
    @Bean
    RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /*确认消息发送成功
        * data：发送数据
        * ack：消息是否成功
        * **/
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            String msgId = data.getId();//消息唯一id
            if (ack) {
                log.info(msgId + ":消息发送成功");
                checkpartSendLogService.updateMailSendLogStatus(msgId, 1);//修改数据库中的记录，消息投递成功
            } else {
                log.info(msgId + ":消息发送失败");
            }
        });
        /**消息从交换机到队列中失败**/
        rabbitTemplate.setReturnCallback((msg, repCode, repText, exchange, routingkey) -> {
            log.info("消息发送失败---没有到queue---可以在重试");
        });
        return rabbitTemplate;
    }

    @Bean
    Queue mailQueue() {
        return new Queue(CheckPartContants.MAIL_QUEUE_NAME, true);
    }

    @Bean
    DirectExchange mailExchange() {
        return new DirectExchange(CheckPartContants.MAIL_EXCHANGE_NAME, true, false);
    }

    @Bean
    Binding mailBinding() {
        return BindingBuilder.bind(mailQueue()).to(mailExchange()).with(CheckPartContants.MAIL_ROUTING_KEY_NAME);
    }

}
